package com.wwj.framework.aspect;

import com.wwj.framework.annotation.SystemControllerLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by yaoan.Xiang on 2015/11/18.
 */
@Aspect
@Component
public class SystemLogAspect {
    private Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    public SystemLogAspect() {
        logger.debug("******************************");
        logger.debug("**      日志监切面启动      **");
        logger.debug("******************************");
    }

    //Controller层切点
    @Pointcut("@annotation(com.wwj.framework.annotation.SystemControllerLog)")
    public void controllerAspect() {
    }

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    private void doBefore(JoinPoint joinPoint) throws Exception {
    }

    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object retVal = null;
        try {

            long startTime = System.currentTimeMillis();
            doBefore(pjp);
            retVal = pjp.proceed();
            long endTime = System.currentTimeMillis();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //HttpSession session = request.getSession();
            //请求的IP
            String ip = request.getRemoteAddr();
            logger.debug("**************************************【操作日志】**************************************");
            logger.debug("** 请求方法:{}", (pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName() + "()"));
            logger.debug("** 方法描述:{}", getControllerMethodDescription(pjp));
            logger.debug("** 请求IP  :{}", ip);
            logger.debug("** 调用时间:{}ms", endTime - startTime);
        } catch (Exception e) {
            logger.error("**************************************【通知异常】**************************************");
            logger.error("** 异常信息:{}", e.getMessage());
        } finally {
            logger.debug("**************************************【日志结束】**************************************");
        }
        return retVal;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    private String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
